/*
 * 文件名               :  ByteArrayInputThread.java
 * 用途                    :  负责从流中读取byte数组
 * 最后修改日期:  $LastChangedDate: 2009-09-14 13:13:18 +0000 (Mon, 14 Sep 2009) $
 * 最后修改者     :  $LastChangedBy: wendal1985@gmail.com $
 * 创建者               :  Wendal Chen <wendal1985@gmail.com>
 */
package com.wendal.java.preproxy.thread;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.Arrays;

import com.wendal.java.preproxy.bean.ByteArrayMessageBean;
import com.wendal.java.preproxy.bridge.BridgeConnector;

public class ByteArrayInputThread extends Thread {

	private Socket socket;
	
	private String from_id;
	
	private BridgeConnector connector;
	
//	private Log log = LogFactory.getLog(getClass());
	
	private boolean flag;
	
	public ByteArrayInputThread( Socket socket,BridgeConnector connector,String from_id) {
		super("ByteArrayInputThread_"+System.currentTimeMillis());
		this.socket = socket;
		this.from_id = from_id;
		this.connector = connector;
	}

	@Override
	public void run() {
		try {
			InputStream is = socket.getInputStream();
			int idle = 0;
			byte [] data = new byte[10 * 1024];
			byte [] tmpDate;
			while(socket.isConnected() && ! socket.isInputShutdown()){
				if(flag) break;
				if(is.available() > 0){
					int len = is.read(data);
					tmpDate = Arrays.copyOf(data, len);
					ByteArrayMessageBean bean = new ByteArrayMessageBean();
					bean.setData(tmpDate);
					bean.setFrom_id(from_id);
					connector.transfer(bean);
					idle = 0;
				}else{
					try {
						Thread.sleep(100);
						idle += 100;
						if(idle > 10 * 1000){//连续10秒收不到数据的话,就结束线程!
							break;
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
						break;
					}
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
//		log.info("线程终止... "+this);
	}
	
	public void setFlag(boolean flag) {
		this.flag = flag;
	}
}